<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="closeDialog(searchParam.plantId)"
            filterable
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            :disabled="searchParam.plantId === ''"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="成品物料">
          <el-select
            v-model="searchParam.materialId"
            placeholder="请选择成品物料"
            :disabled="searchParam.plantId === ''"
            filterable
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in materials"
              :key="item.id"
              :label="`${item.materialCode}-${item.materialName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="stopParam()"
          ><i-ep-delete />批量停用</el-button
        >
        <!-- <el-button type="primary"  @click="excelBoxOpen"
          >导入
        </el-button> -->
        <!-- <el-button @click="dailyBatchImport"
          ><template #icon><i-ep-upload /></template>导入日计划</el-button
        > -->
        <el-button
          type="primary"
          class="ml-3"
          :disabled="ids.length === 0"
          @click="exportData()"
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-dialog
          :close-on-click-modal="false"
          title="生产版本导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/mes/mesroutingallocation/exportTemp',
                  '生产版本上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              生产版本上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工艺路线"
          prop="routingCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="版本编号"
          prop="versionNo"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="成品物料"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-show="scope.row.materialCode">
              {{ `${scope.row.materialCode}-${scope.row.materialName}` }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="工作中心"
          prop="workCenterCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-show="scope.row.workCenterCode">
              {{ `${scope.row.workCenterCode}-${scope.row.workCenterName}` }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="BOM"
          prop="bomCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-show="scope.row.bomCode">
              {{ `${scope.row.bomCode}-${scope.row.bomName}` }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="图号"
          prop="figureNumber"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料默认版本"
          prop="isDefault"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.isDefault === 1">是</el-tag>
            <el-tag v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="修改时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="修改人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <!-- <el-button
              type="primary"
              size="small"
              link
              :loading="copyLoading"
              @click="openDialogs(scope.row, true)"
            >
              复制
            </el-button> -->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesroutingallocation-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESROUTINGALLOCATION",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesroutingallocation/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  materialId: "",
  workCenterId: "",
};

const deleteParam = {
  api: "/mes/mesroutingallocation/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesroutingallocation/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开工艺路线分配物料表单弹窗 */
function openDialog(roleObj?: Object) {
  console.log({ ids: ids.value });

  if (roleObj) {
    addDialog.title = "修改生产版本";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增生产版本";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开工艺路线分配物料表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "工艺路线分配物料详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
  //closeDialog(searchParam.plantId);
  getWorkshopList(plantList.value[0].id);
  getMaterials(plantList.value[0].id);
};
const copyLoading = ref(false);
/** 打开生产订单表单弹窗 详情 */
function openDialogs(roleObj?: any, isReadonly?: boolean) {
  ElMessageBox.confirm("确定复制吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      copyLoading.value = true;
      const res: any = await request({
        url: `/mes/mesrouting/copy/${roleObj.id}`,
        method: "get",
      }).finally(() => {
        copyLoading.value = false;
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "复制成功",
        });
      }
      getTableList();
    })
    .catch(() => {});
}
function closeDialog(plantId: String) {
  getWorkshopList(plantId);
  getMaterials(plantId);
}
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};
//成品物料
const materials = ref([]);
async function getMaterials(plantId: String) {
  if (plantId) {
    await request({
      url: "mdm/mdmmaterial/getProductionList",
      method: "post",
      // data: { plantId: formData.plantId, enabled: 1, materialType: 3 },
      data: { plantId: plantId },
    }).then((res) => {
      materials.value = res.data;
    });
  }
}
//批量停用
const stopParam = async () => {
  ElMessageBox.confirm("确定批量停用吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await request({
        url: "/mes/mesroutingallocation/disabled",
        method: "post",
        data: { ids: ids.value },
      });
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "批量停用成功",
        });
      }
      getTableList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消停用",
      });
    });
};

// 导出
const exportData = () => {
  if (ids.value.length > 0) {
    let idss = { ids: ids.value };
    useDownload(
      "/mes/mesroutingallocation/export",
      "生产版本",
      idss,
      true,
      ".xls"
    );
  }
};

// 导入excel
const uploadApi = "/mes/mesroutingallocation/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request.post(uploadApi, formdata, config).then((res) => {
    ElMessage({
      type: "success",
      message: "上传成功！",
    });

    excelBox.value = false;
    uploadBtn.value = false;
    search();
  });
}
</script>
